package org.quincy.rock.core.dao.sql;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.quincy.rock.core.dao.NameInterceptor;
import org.quincy.rock.core.dao.ValueInterceptor;
import org.quincy.rock.core.util.CoreUtil;
import org.quincy.rock.core.util.StringUtil;

/**
 * <b>FromTable。</b>
 * <p><b>详细说明：</b></p>
 * <!-- 在此添加详细说明 -->
 * 无。
 * 
 * @version 1.0
 * @author wks
 * @since 1.0
 */
public class FromTable extends AbstractExpression {

	/**
	 * serialVersionUID。
	 */
	private static final long serialVersionUID = 416098118881805609L;

	/**
	 * 表名。
	 */
	private String tableName;

	/**
	 * 表别名。
	 */
	private String tableAlias;

	/**
	 * join连接表。
	 */
	private List<JoinOn> joinTables;

	public FromTable() {
		super();
	}

	protected FromTable(String tableName, String tableAlias) {
		this.tableName = tableName;
		this.tableAlias = tableAlias;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public String getTableAlias() {
		return tableAlias;
	}

	public void setTableAlias(String tableAlias) {
		this.tableAlias = tableAlias;
	}

	public List<JoinOn> getJoinTables() {
		if (joinTables == null)
			joinTables = new ArrayList<>();
		return joinTables;
	}

	public void setJoinTables(List<JoinOn> joinTables) {
		this.joinTables = joinTables;
	}

	public FromTable addJoinTable(JoinOn joinTable) {
		this.getJoinTables().add(joinTable);
		return this;
	}

	public boolean hasAlias() {
		return StringUtils.isNotBlank(tableAlias);
	}

	public boolean hasJoin() {
		return !CoreUtil.isEmpty(joinTables);
	}

	public boolean isEmpty() {
		return StringUtil.isBlank(tableName);
	}

	@Override
	public StringBuilder build(StringBuilder buffer, NameInterceptor nameInterceptor,
			ValueInterceptor valueInterceptor) {
		buffer.append("from ").append(nameInterceptor == null ? tableName : nameInterceptor.applyTableName(tableName));
		if (hasAlias())
			buffer.append(StringUtil.CHAR_SPACE).append(getTableAlias());
		if (hasJoin()) {
			for (JoinOn joinTable : joinTables) {
				buffer.append(StringUtil.CHAR_SPACE);
				joinTable.build(buffer, nameInterceptor, valueInterceptor);
			}
		}
		return buffer;
	}

}
